#!/usr/local/bin/perl
package FT;
use strict; use warnings;
no if $] >= 5.018, warnings => "experimental::smartmatch";
use feature qw/switch/;

our $FT_TAR   =  1;
our $FT_ZIP   =  2;
our $FT_GZIP  =  3;
our $FT_BZIP2 =  4;
our $FT_7ZIP  =  5;
our $FT_XZ    =  6;
our $FT_RAR   =  7;
our $FT_PDF   =  8;
our $FT_PS    =  9;
our $FT_EPS   = 10;

our %coms=(
    $FT_TAR   => "tar",
    $FT_ZIP   => "unzip",
    $FT_GZIP  => "gzip",
    $FT_BZIP2 => "tar",
    $FT_7ZIP  => "7z",
    $FT_XZ    => "tar",
    $FT_RAR   => "unrar",
    $FT_PDF   => "gs",
    $FT_PS    => "gs",
    $FT_EPS   => "gs");

my $gsopts=
    "-q -dSAFER -dNOPAUSE -dBATCH"
    ." -sDEVICE=png256" # or pngalpha
    ." -r200" # dpi
    ." -dTextAlphaBits=4 -dGraphicsAlphaBits=4";# or 2 or 1

our %args=(
    $FT_TAR   => "xvf '%f' -C '%d'",
    $FT_ZIP   => "-o -P '%p' -O CP932 '%f' -d '%d'",
    $FT_GZIP  => "-d '%f'",
    $FT_BZIP2 => "xvfj '%f' -C '%d'",
    $FT_7ZIP  => "x -o'%d' -p'' '%f'",
    $FT_XZ    => "xvfJ '%f' -C '%d'",
    $FT_RAR   => "x -c- -p%p- -o+ -r -y '%f' '%d'",
    $FT_PDF   => "$gsopts %u -sOutputFile='%o' '%f'",
    $FT_PS    => "$gsopts %u -sOutputFile='%o' '%f'",
    $FT_EPS   => "$gsopts -dEPSCrop %u -sOutputFile='%o' '%f'");

sub get_com
{
    my ($ft,%as)=@_;
    return unless exists $coms{$ft};
    return unless exists $args{$ft};
    my $a=$args{$ft};
    while($a=~/(%[\w][-]*)/g){ # %p- is replaced by - if %p is blank
	my $k=$1;
	my $d;
	if(length($k)>2){
	    $d=substr($k,2);
	    $k=substr($k,0,2);
	}
	return unless exists $as{$k}; # internal error
	($b=$as{$k})=~s/%%/x01/g;
	if(defined($d)){
	    $b=$d unless $b;
	    $k.=$d;
	}
	$a=~s/$k/$b/;
    }
    $a=~s/x01/%/g;
    return $coms{$ft}." ".$a." 1>&2"; # stdout is used by another thread.
}

sub is_available
{
    return 1 if(exists($coms{$_[0]})&&system("which ".$coms{$_[0]})==0);
}

sub is_archive
{
    given($_[0]){
	return 1 when([$FT_TAR,
		       $FT_ZIP,
		       $FT_GZIP,
		       $FT_BZIP2,
		       $FT_7ZIP,
		       $FT_XZ,
		       $FT_RAR]);
    }
}
sub to_convert
{
    given($_[0]){
	return 1 when([$FT_PDF,
		       $FT_PS,
		       $FT_EPS]);
    }
}

1;
